<template>
    <div class="callcenter-product-info">
        <template v-if="callDetail.recordId">
            <header class="header">
                <select-product 
                    ref="productSelect" 
                    :key="callDetail.recordId"
                    :placeholder="$t('callcenter.placeholder2')" 
                    :selected-product="productIds"
                    @input="selectProduct"
                ></select-product>
                <el-button type="primary" @click="submit">{{ $t('common.base.makeSure') }}</el-button>
            </header>

            <div class="main-name">
                {{ product.name }}
            </div>
            <!-- 表单 -->
            <form-view v-loading="formViewLoading" v-if="isShowFormView" :fields="fields" :value="product"
                class="task-tab-container task-view-containner tab-container bbx-cell-form-view">
                <div slot="name"></div>
                <template slot="createUser" slot-scope="{ value }">
                    <div v-if="value" class="form-view-row bbx-form-cell-item">
                        <label>{{ $t('common.base.createUser') }}</label>
                        <div class="form-view-row-content">
                            <span v-user="value.userId" class="user-card-triggle">
                                <template v-if="isOpenData">
                                    <open-data type="userName" :openid="product.createUserStaffId"></open-data>
                                </template>
                                <template v-else>
                                    <span>{{ value.displayName }}</span>
                                </template>
                            </span>
                        </div>
                    </div>
                </template>
                <template slot="isRepeatRepair" slot-scope="{ field, value }">
                    <div class="form-view-row bbx-form-cell-item">
                        <label>{{ $t('product.detail.type.isRepeatRepair') }}</label>
                        <div class="form-view-row-content" :style="{ color: field.setting.color || '#F4882f' }">
                            {{ value || $t('common.base.no') }}
                        </div>
                    </div>
                </template>
                <template slot="customer" slot-scope="{ value }">
                    <div class="form-view-row bbx-form-cell-item">
                        <label>{{ $t('common.base.customer') }}</label>
                        <div class="form-view-row-content form-view-row-customer">
                            <span class="link" v-if="product.customerName">
                                {{ product.customerName }}
                            </span>
                            <span class="unbind" v-else>
                                {{ $t('common.base.notContact') }}
                            </span>
                        </div>
                    </div>
                    <div class="form-view-row bbx-form-cell-item" v-if="value && hasLinkman">
                        <label>{{ $t('common.base.contact') }}</label>
                        <div class="form-view-row-content">
                            {{ product.linkman && product.linkman.name + ' ' + product.linkman.phone }}
                        </div>
                    </div>
                    <form-address-view class="bbx-form-cell-item" v-if="value && hasAddress"
                        :field="{ displayName: $t('product.type.customerAddress') }" :value="product.address">
                    </form-address-view>
                </template>

                <div slot="qrcodeId" slot-scope="{ value }"></div>
                <template slot="catalogId" slot-scope="{ value }">
                    <div v-if="productInfo && productInfo.catalogId" class="form-view-row product-type bbx-form-cell-item">
                        <label>{{ $t('common.base.productType') }}</label>
                        <div class="flex-1">
                            <el-tooltip effect="dark" :content="productInfo.type" placement="bottom-start">
                                <div class="overHideCon-1">
                                    <span>
                                        {{ productInfo.type }}
                                    </span>
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                </template>

                <template slot="createTime" slot-scope="{ value }">
                    <div class="form-view-row bbx-form-cell-item" v-if="value">
                        <label>{{ $t('common.base.createTime') }}</label>
                        <div class="form-view-row-content">
                            <span>{{ value | fmt_datetime }}</span>
                        </div>
                    </div>
                </template>

                <!-- 产品目录 -->
                <template slot="productMenu" slot-scope="{ field }">
                    <div class="form-view-row bbx-form-cell-item">
                        <label>{{ field.displayName }}</label>
                        <div class="form-view-row-content">
                            {{ productInfo.productMenu }}
                        </div>
                    </div>
                </template>

                <!-- start 产品负责人 -->
                <template slot="productManager" slot-scope="{ field }">
                    <div class="form-view-row bbx-form-cell-item">
                        <label>{{ field.displayName }}</label>
                        <div class="form-view-row-content">
                            <span v-user="productInfo.productManager" class="user-card-triggle">
                                <template v-if="isOpenData">
                                    <open-data type="userName" :openid="productInfo.productManagerStaffId"></open-data>
                                </template>
                                <template v-else>
                                    {{ productInfo.productManagerName }}
                                </template>
                            </span>
                        </div>
                    </div>
                </template>
                <!-- end 产品负责人 -->
            </form-view>
        </template>

        <template v-else>
            <no-data-view-new />
        </template>
    </div>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue';
// components
import SelectProduct from './SelectProduct.vue';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
// api
import { addCallRecordAndProducts } from '@src/api/CallCenterApi.js';
import {
    getProductFields,
    getProductDetail,
} from '@src/api/ProductApi';
// model
import MsgModel from '@model/MsgModel';
// utils
import { message } from '@src/util/message';
import { smoothQualityInfoFieldForFormView, buildQualityInfoFormDataForFormView } from '@service/QualityInfoService.ts';
import i18n from '@src/locales';
import { isOpenData } from '@src/util/platform';
import { debounce } from 'lodash';

export default {
    name: 'callcenter-product-info',
    components: {
        [SelectProduct.name]: SelectProduct,
        NoDataViewNew,
    },
    props: {
        callDetail: {
            type: Object,
            default: () => ({}),
        },
    },
    emits: ['submit'],
    setup(props, { emit }) {
        const productSelect = ref(null);
        const form = reactive({
            productId: '',
            recordId: '',
        });

        const selectProduct = data => {
            const val = (data || []).map(x => x.id);
            form.productId = val?.[0] || '';
        };
        const submit = debounce(async () => {
            try {
                form.recordId = props.callDetail.recordId;

                const res = await addCallRecordAndProducts({
                    recordId: form.recordId,
                    productIds: [form.productId],
                });

                if (MsgModel.isSuccess(res)) {
                    initFormView();
                } else {
                    message.error(res.message);
                }
            } catch (e) {
                console.log('submit: ', e);
            }
        }, 300);

        // ============================ form-view 数据获取 ============================
        const dynamicProductFields = ref([]);
        const productInfo = ref({});
        const isShowFormView = ref(false);
        const formViewLoading = ref(false);

        // 获取产品字段
        const getFields = async () => {
            try {
                const res = await getProductFields({ isFromSetting: false });
                if (res.status !== 0) return message.error(res.message);

                dynamicProductFields.value = res.data || [];
                isShowFormView.value = true;
            } catch (e) {
                console.error('e', e)
            }
        }

        const getProductInfo = async () => {
            try {
                formViewLoading.value = true;
                const res = await getProductDetail({ id: form.productId });
                formViewLoading.value = false;
                if (!res) return;

                productInfo.value = res;
            } catch (e) {
                formViewLoading.value = false;
                console.error('e', e)
            }
        }

        const product = computed(() => {
            return {
                ...productInfo.value,
                ...buildQualityInfoFormDataForFormView(productInfo.value)
            }
        })
        const fields = computed(() => {
            let fixedFields = [
                {
                    displayName: '',
                    formType: 'separator',
                },
                {
                    displayName: i18n.t('common.base.createUser'),
                    fieldName: 'createUser',
                    formType: 'user',
                    isSystem: 1,
                    orderId: 10001,
                },
                {
                    displayName: i18n.t('common.base.createTime'),
                    fieldName: 'createTime',
                    formType: 'datetime',
                    isSystem: 1,
                    orderId: 10002,
                },
                {
                    displayName: i18n.t('product.detail.type.id'),
                    fieldName: 'id',
                    formType: 'text',
                    isSystem: 1,
                    orderId: 10003,
                },
            ];

            const fields = dynamicProductFields.value.concat(fixedFields).sort((a, b) => a.orderId - b.orderId);
            return smoothQualityInfoFieldForFormView(fields);
        })

        const hasLinkman = () => {
            let field = dynamicProductFields.value.filter(
                (item) => item.formType == 'customer'
            )[0];
            return field && field.setting.customerOption?.linkman;
        }
        const hasAddress = () => {
            let field = dynamicProductFields.value.filter(
                (item) => item.formType == 'customer'
            )[0];
            return field && field.setting.customerOption?.address;
        }
        const productIds = computed(() => {
            return props.callDetail.productIds || [];
        })

        const initFormView = () => {
            if(!form.productId) {
                isShowFormView.value = false;
                return;
            }
            emit('submit', form.productId);

            getFields();
            getProductInfo();
        }

        watch(
            () => props.callDetail,
            (val) => {
                emit('submit', '');
                if(val?.productIds?.length) {
                    form.productId = val.productIds[0];
                    initFormView();
                }
            }
        )

        return {
            productSelect,
            form,
            product,
            fields,
            isShowFormView,
            productInfo,
            isOpenData,
            productIds,
            formViewLoading,
            hasLinkman,
            hasAddress,
            selectProduct,
            submit,
        };
    },
};
</script>

<style lang="scss" scoped>
.callcenter-product-info {
    .header {
        width: 100%;
        display: flex;

        .el-button {
            margin-left: 8px;
        }
    }
    .main-name {
        color: #262626;
        font-size: 14px;
        font-weight: 700;
        word-break: break-all;
        padding: 20px 10px 0;
    }
}
</style>
